﻿using Himp.TaskScheduling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.ObjectMapping;

namespace Himp.Workflows
{
    /// <summary>
    /// 流程定义服务
    /// </summary>
    public class WorkflowDefinitionService : TaskSchedulingAppService, IWorkflowDefinitionService
    {
        private ActiviWorkflowManager _workflowManager;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="workflowManager"></param>
        public WorkflowDefinitionService(ActiviWorkflowManager workflowManager)
        {
            _workflowManager = workflowManager;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<WorkflowModelDto>> GetListAsync(ProcessDefinitionInput input)
        {
            var list = await _workflowManager.GetWorkflowModel(input.Status);
            var itemsDto = ObjectMapper.Map<List<WorkflowModel>, List<WorkflowModelDto>>(list);

            if (input.Pi == 0)
            {
                return new PagedResultDto<WorkflowModelDto>(itemsDto.Count, itemsDto);
            }
            else
            {
                var totalCount = itemsDto.Count();
                var pagedItems = itemsDto.Skip((input.Pi - 1) * input.Ps).Take(input.Ps);

                return new PagedResultDto<WorkflowModelDto>(totalCount, pagedItems.ToList());
            }
        }

        /// <summary>
        /// 部署
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<WorkflowInstanceStasDto> PostDeployAsync(WorkflowDeployDto input)
        {
            var stas = await _workflowManager.DeployWorkflowModel(input.Id, input.WorkflowName);
            var itemDto = ObjectMapper.Map<WorkflowInstanceStas, WorkflowInstanceStasDto>(stas);

            return itemDto;
        }

        /// <summary>
        /// 激活/挂起
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<WorkflowInstanceStasDto> PostActivateAsync(WorkflowActivateDto input)
        {
            var stas = await _workflowManager.ActivateWorkflowModel(input.DeploymentKey);
            var itemDto = ObjectMapper.Map<WorkflowInstanceStas, WorkflowInstanceStasDto>(stas);

            return itemDto;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<WorkflowInstanceStasDto> DeleteAsync(string id)
        {
            var stas = await _workflowManager.DeleteWorkflowModel(id);
            var itemDto = ObjectMapper.Map<WorkflowInstanceStas, WorkflowInstanceStasDto>(stas);

            return itemDto;
        }
    }
}
